package com.fileupload.fileupload.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fileupload.fileupload.dao.UploadExcelEntityDao;
import com.fileupload.fileupload.domain.entity.UploadExcelEntity;
import com.fileupload.fileupload.handler.MyWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ExcelDataListener extends AnalysisEventListener<UploadExcelEntity> {

    private List<UploadExcelEntity> dataList = new ArrayList<>();

    @Autowired
    private UploadExcelEntityDao uploadExcelEntityDao;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    /**
     * 每解析一行数据都会回调此方法
     * @param uploadExcelEntity
     * @param analysisContext
     */
    @Override
    public void invoke(UploadExcelEntity uploadExcelEntity, AnalysisContext analysisContext) {
        dataList.add(uploadExcelEntity);
        log.info("解析到一条数据：{}", uploadExcelEntity);
        if (dataList.size() >= 500){
            log.info("开始向数据库中批量插入500条数据");
            // 批量入库
            uploadExcelEntityDao.insertExcelDate(dataList);
            // 清空集合
            dataList.clear();
        }
    }

    /**
     * 解析完成之后会回调此方法
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try {
            if (!dataList.isEmpty()){
                // 插入剩余的数据
                uploadExcelEntityDao.insertExcelDate(dataList);
            }
            log.info("excel文件解析完成");
            // todo 发送websocket通知
            myWebSocketHandler.sendMessageToClient("excel文件解析完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
